﻿using System;
using Microsoft.SharePoint;

namespace SPRepository
{
    public class SingleUserFieldType : SimpleFieldType<UserFieldDto>
    {
        public SingleUserFieldType(Guid id) : base(id)
        {
        }

        private SPFieldUserValue GetSPFieldUserValue(SPListItem item)
        {
            var web = item.ParentList.ParentWeb;
            var value = GetFieldRawValue(item);
            if (value == null)
            {
                return null;
            }
            return new SPFieldUserValue(web, value.ToString());
        }

        public override UserFieldDto GetValue(SPListItem item)
        {
            var fieldValue = GetSPFieldUserValue(item);
            if (fieldValue == null)
            {
                return null;
            }
            return new UserFieldDto(fieldValue.LookupId, fieldValue.LookupValue, fieldValue.SipAddress,
                                    fieldValue.User.ConvertToDto());
        }

        public override void SetValue(SPListItem item, UserFieldDto value)
        {
            var fieldValue = GetSPFieldUserValue(item);
            if (value != null)
            {
                fieldValue.LookupId = value.LookupId;
            }
            item[FieldId] = fieldValue;
        }
    }
}